import { _decorator, director, Vec3 } from 'cc'
import { DragAnimator, DragAnimatorOptions, ZController } from '../../Zcc'
import { ShakerState } from '../../types/StateEnums'

const { ccclass } = _decorator

@ccclass('ShakerController')
export class ShakerController extends ZController {
	private dragAnimator: DragAnimator
	/** 骰盅状态 */
	private shakeState: ShakerState = ShakerState.CLOSE

	getState(): ShakerState {
		return this.shakeState
	}
	/** 设置拖拽的起始位置和目标位置 */
	setPosRange(start: Vec3, target: Vec3) {
		if (!this.dragAnimator) {
			const options: DragAnimatorOptions = {
				node: this.node,
				startPos: new Vec3(0, 0, 0),
				targetPos: new Vec3(0, 100, 0),
				animDuration: 0.18,
				dragEnabled: true,
				callbacks: {
					onDragStart: this.handleDragStart.bind(this),
					onDragProgress: this.handleDragProgress.bind(this),
					onDragComplete: this.handleDragComplete.bind(this)
				}
			}
			this.dragAnimator = new DragAnimator(options)
		}
		this.dragAnimator.setPosRange(start, target)
	}

	/** 设置是否启用拖拽 */
	setDragEnabled(enabled: boolean) {
		this.dragAnimator.setDragEnabled(enabled)
	}
	closeShaker() {
		this.dragAnimator.playAnimation(false)
	}
	openShaker() {
		this.dragAnimator.playAnimation(true)
	}
	private handleDragStart() {
		// 处理拖拽开始
		this.shakeState = ShakerState.ANIMATING
	}

	private handleDragProgress(progress: number) {
		// 处理拖拽进度
		this.shakeState = ShakerState.ANIMATING
	}

	private handleDragComplete(isToTarget: boolean) {
		// 处理拖拽完成
		if (isToTarget) {
			this.shakeState = ShakerState.OPEN
			director.emit('onShaker', ShakerState.OPEN)
		} else {
			this.shakeState = ShakerState.CLOSE
			director.emit('onShaker', ShakerState.CLOSE)
		}
	}

	onDestroy() {
		this.dragAnimator.destroy()
	}
}
